<template>
    <div style="background-color: #ffffff;">
        <!-- :before-change="beforeChange" -->
        <!-- <HeadNav :title="'留存填报'" :leftArrow="true"></HeadNav> -->
        <!-- 周月年 -->
        <div class="content">
            <div class="imageBox" :class="[!dishInfo.dishImage ? 'imageBox_Border':'imageBox_noBorder' ]">
                <img v-if="!dishInfo.dishImage"  @click="openCamera" src="../../assets/images/photoIcon.png" alt="点击拍照上传" style="cursor: pointer;" class="camera">
                <div v-if="!dishInfo.dishImage">点击拍照上传</div>
                <!-- 隐藏的文件输入元素 -->
                <!-- <input type="file" ref="fileInput" accept="image/*" style="display: none;" @change="handleFileChange" /> -->
                <!-- 隐藏的文件输入元素 -->
                <input type="file" ref="fileInput" accept="image/*" capture="camera" style="display: none;"
                    @change="handleFileUpload" />
                <!-- 展示上传的图片 -->
                <img v-if="dishInfo.dishImage" :src="dishInfo.dishImage" alt="上传的图片" style="max-width: 100%;" @click="openCamera" class="picture" mode="widthFix"/>
            </div>
            <div class="recordList recordList_pb">
                <div class="recordInfoItem name">
                    <!-- <div class="label">填报时间</div>
                    <div class="text">{{currentDate}}</div> -->
                   <van-field label="填报时间" v-model="currentDate" :border="false" disabled/>
                </div>
                <div class="recordInfoItem name">
                    <!-- <van-field v-model="value" label="菜品名字" placeholder="填写菜品名称"/>
                    <div class="selectBtn" @click="showSelectList">
                        <van-icon :name="showSheet ? 'arrow-up' : 'arrow-down'" size="11" />
                    </div> -->
                    <van-field v-model="dishInfo.dishName" label="菜品名字" placeholder="填写菜品名称" :right-icon="showSheet ? 'arrow-up' : 'arrow-down'" @input="inputEvent" @click-right-icon="showSelectList" clearable/>
                </div>
                <div class="recordInfoItem describe">
                    <div class="label" style="padding-top: 20px;">菜品描述</div>
                    <van-field v-model="dishInfo.description" rows="2" autosize type="textarea" maxlength="100"
                        placeholder="填写菜品的原材料信息" :show-word-limit="true" clearable/>
                </div>
                <div class="recordInfoItem describe remark">
                    <div class="label" style="padding-top: 20px;">备注</div>
                    <van-field v-model="dishInfo.remarks" rows="2" autosize type="textarea" maxlength="30"
                        placeholder="填写菜品备注信息" :show-word-limit="true" clearable/>
                </div>
            </div>
            <div class="applyBtn">
                <van-button type="primary" class="page_submit_btn" @click="toShowPopupSubmit()"> {{ handle==='add' ? '确认填报' : '确认修改'}} </van-button>
            </div>
        </div>
        <!-- <foot></foot> -->
        <van-popup v-model="showTipsSingle" :closeable="true" round style="width: 80%;padding-bottom: 24px;">
            <!-- <div class="top_title">你确定提交当前留存菜品信息吗？</div> -->
            <div class="top_title" v-if="handle==='add'">你确定提交当前留存菜品信息吗？</div>
            <div class="top_title" v-if="handle==='edit'">你确定提交当前修改的留存菜品信息吗？</div>
            <div class="sub_btn" :class="{ disabled: isSubmitting }" @click="!isSubmitting && handle==='add' ? submitToApply() : null"  v-if="handle==='add'">
                确定
            </div>
            <div class="sub_btn" :class="{ disabled: isSubmitting }" @click="!isSubmitting && handle==='edit' ? submitToEdit() : null"  v-if="handle==='edit'">
                确定
            </div>
        </van-popup>
        <van-action-sheet v-model="showSheet" :actions="actions" @select="onSelect" cancel-text="取消"
            close-on-click-action @cancel="onCancel" />
    </div>
</template>

<script>
/* eslint-disable */
import { getParams } from '@/common/public'
import HeadNav from '@/components/HeadNav'
import foot from '../foot/foot.vue'
import { stsApi} from '@/api/sts'
import { Toast } from 'vant'
import OSS from 'ali-oss'
import {addDishSampleApi,getListByNameApi,getDishSampleByIdApi,updateDishSampleApi} from '@/api/stall'


export default {
    name: 'PreserveApply',
    components: {
        HeadNav,
        foot
    },
    computed: {
        // ...mapState({
        //     token: (state) => state.applyrecords.token
        // })
    },
    watch: {
        active(newVal) {
            console.log('newVal', newVal)
            if (newVal === 0) {

            } else if (newVal === 0) {

            } else {

            }
        }
    },
    data() {
        return {
            active: 0,
            loading: true,

            show: true,
            current: 0,
            currentItem: -1,
            showTipsSingle: false,
            popupItem: undefined,
            currentDate:null, //当前填报时间
            dishInfo:{
                dishName: undefined, //菜品名称
                remarks: undefined, //备注信息
                description: undefined, //描述信息   
                dishImage: null, // 用于存储上传的图片    
            },
            showSheet: false, //显示选择弹窗
            actions: [
                // { name: '麻婆豆腐' }, { name: '酸菜鱼' }, { name: '麻辣香锅' }
            ],  //选择列表   
            selectedFile: null,      // 用户选择的文件 
            ossClient: null,
            fileName:undefined,
            handle:'add',
            stsTokenInfo:undefined,
            dishId:undefined,
            uploadImg:null,   //上传图片
            isSubmitting: false, // 新增提交状态标识
        }
    },

    beforeRouteEnter(to, from, next) {
        next((vm) => {
            if(to.query.item){
                vm.localData = JSON.parse(to.query.item)
                vm.handle=vm.localData.handle
                console.log(vm.localData,vm.handle)
                if(vm.localData.id){
                    vm.dishId = vm.localData.id
                }
            }
        })
    },
    mounted() {
        this.loading = false
        this.setCurrentDate()
        this.getSTSToken()  
        if(this.dishId && this.handle==='edit'){
            this.getOneDishSample(this.dishId)
        }
        this.getDishNameList()
    },
    created() {

    },

    methods: {
        // base64转blob
        dataURLtoBlob(dataurl) {
            var bstr = atob(dataurl),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr]);
        },
        // handleClick() {
        //     // let filesName = new Date().getTime().toString()+'name'
        //     // console.log('222',filesName)
        //     // console.log('ios',window.ccworkBridge)
        //     // window.ccworkBridge.ccworkGetPicsFromAlbumV2({
        //     //   maxNum:6,
        //     //   mType:0,
        //     //   piciterable(file,data){
        //     //     console.log('aa',file,data)
        //     //   },
        //     // }
        //     window.ccworkBridge.ccworkGetPicsFromAlbum({
        //         // quality:'mid',
        //         // mode:'both',
        //         // piciterable(fileDta){
        //         //   let fileName=fileDta
        //         // }
        //         maxNum: 9,
        //         mType: 0
        //     }
        //         , (e) => {
        //             console.log('result', e);

        //             e.result.forEach((item, index) => {
        //                 let filesName = new Date().getTime().toString() + 'name' + index
        //                 console.log('222', filesName)
        //                 client().multipartUpload(filesName, this.dataURLtoBlob(item.content))
        //                     .then(result => {
        //                         console.log('上传成功', result)
        //                         if (result.res.statusCode == 200) {
        //                             // resolve(result.res);
        //                             let fileUrl = result.res.requestUrls[0] ? result.res.requestUrls[0].split('?')[0] : ''
        //                             // _this.submit_file.push(detail.name.v_model);
        //                             var img_list = {
        //                                 url: fileUrl
        //                             }
        //                             this.fileList2.push(fileUrl)
        //                             // resolve(result)
        //                         } else {
        //                             this.$toast('上传出错')
        //                         }
        //                     })
        //                     .catch(err => {
        //                         console.log('失败', err)
        //                         // reject();
        //                     })
        //             })

        //         })
        // },
        
        // Set current date
        setCurrentDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            this.currentDate = `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`;
        },
        
        

        // 留存填报
        toPreserveApply() {
            this.$route.push({
                path: '/preserveDishes'
            })
        },

        //输入框信息改变  显示列表
        inputEvent(e){
            console.log(e,'e')
            getListByNameApi({dishName:e}).then(res=>{
                if(res.code===200){

                }
            })
        }, 

        // 获取产品列表
        getDishNameList () {
            getListByNameApi({dishName:this.dishName}).then(res=>{
                if(res.code===200){
                    const dishList = []
                    if(res.data.length > 0){
                        res.data.forEach((ele) => {
                            dishList.push(
                                Object.assign({},{ name:ele.dishName, id:ele.id})
                            )
                        })
                    }
                    if(dishList.length > 0){
                        this.actions=dishList
                    }else{
                        this.actions=[]
                    }
                }
            })
        },

        // 显示选择列表
        showSelectList() {
            this.showSheet = true
        },
        // 选择
        onSelect(item) {
            // 默认情况下点击选项时不会自动收起
            // 可以通过 close-on-click-action 属性开启自动收起
            this.showSheet = false;
            this.dishInfo.dishName=item.name
            Toast(item.name);
            getDishSampleByIdApi(item.id).then(res => {
                if(res.code == 200){
                    this.dishInfo.remarks = res.data.remarks
                    this.dishInfo.description = res.data.description
                }
            })



        },
        //取消  --- 关闭弹窗
        onCancel() {
            Toast('取消')
            this.showSheet = false
        },


        // 调起手机相机 相册 文件
        // openCamera() {
        //     this.$refs.fileInput.click();
        // },
        // handleFileChange(event) {
        //     const file = event.target.files[0];
        //     if (file) {
        //         this.selectedFile = file;
        //         this.previewImage(file);
        //     }
        // },
        // previewImage(file) {
        //     const reader = new FileReader();
        //     reader.onload = (e) => {
        //         this.imageSrc = e.target.result
        //     }
        //     reader.readAsDataURL(file)
        // },
        // uploadImage() {
        //     if (this.selectedFile) {
        //         const formData = new FormData();
        //         formData.append('file', this.selectedFile);

        //         axios.post('/upload', formData, {
        //             headers: {
        //                 'Content-Type': 'multipart/form-data'
        //             }
        //         })
        //             .then(response => {
        //                 console.log('上传成功', response.data);
        //             })
        //             .catch(error => {
        //                 console.error('上传失败', error);
        //             });
        //     } else {
        //         console.warn('没有选择文件');
        //     }
        // },
        
        // 2 打开相机
        openCamera() {
            this.$refs.fileInput.click();
        },

        // 处理文件上传
        // handleFileUpload(event) {
        //     const file = event.target.files[0];
        //     if (file) {
        //         const reader = new FileReader();
        //         reader.onload = (e) => {
        //             this.dishImage = e.target.result; // 将图片数据赋值给dishImage
        //         };
        //         reader.readAsDataURL(file); // 读取文件内容
        //     }
        // },

        //  // 处理文件上传
         async handleFileUpload(event) {
            const file = event.target.files[0];
            if (file) {
                // this.selectedFile=file
                console.log('屏幕尺寸:', window.screen.width);
                const compressedFile = await this.compressImage(file, 0.6, window.screen.width * 2);
                this.selectedFile = compressedFile
                const reader = new FileReader();
                reader.onload = async (e) => {
                    this.dishInfo.dishImage = e.target.result; // 将图片数据赋值给dishImage
                };
                reader.readAsDataURL(compressedFile); // 读取文件内容
            }
        },
        // 页面的确认按钮
        toShowPopupSubmit(item) {
            console.log(item);
            this.popupItem = item
            this.showTipsSingle = true
        },
        async getSTSToken() {
            // const response = await fetch('/sts-token');
            // return await response.json();
            stsApi().then(res=>{
                console.log(res,'sts')
                if(res.code==200){
                    this.stsTokenInfo=res.data
                    this.ossClient = new OSS({
                        region: 'oss-cn-beijing',
                        accessKeyId: this.stsTokenInfo.accessKeyId,
                        accessKeySecret: this.stsTokenInfo.accessKeySecret,
                        bucket: '17lelife-bucket',
                        stsToken: this.stsTokenInfo.stsToken,

                        refreshSTSToken: async () => {
                            const newRes = await stsApi();
                            if (newRes.code === 200) {
                                const newStsData = newRes.data;
                                return {
                                    accessKeyId: newStsData.accessKeyId,
                                    accessKeySecret: newStsData.accessKeySecret,
                                    stsToken: newStsData.stsToken
                                };
                            }
                            // throw new Error('Failed to refresh STS token');
                        },
                        // 假设 STS 令牌有效期为 1 小时，提前 10 分钟刷新
                        refreshSTSTokenInterval: 50 * 60 * 1000 
                    })
                }
            })
        },

        compressImage(file, quality = 0.6,maxWidth = 1200) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    const img = new Image();
                    img.src = e.target.result;
                    img.onload = function () {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        // canvas.width = img.width;
                        // canvas.height = img.height;
                        const screenMax = Math.max(window.screen.width, window.screen.height) * 1.5;
                        const finalMaxWidth = Math.min(maxWidth, screenMax);

                        const scale = finalMaxWidth / img.width;
                        canvas.width = finalMaxWidth;
                        canvas.height = img.height * scale;
                        console.log('原始尺寸:', img.width, '压缩后:', canvas.width);
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        canvas.toBlob((blob) => {
                            resolve(new File([blob], file.name, { type: file.type }));
                        }, file.type, quality);
                    };
                    img.onerror = reject;
                };
                reader.onerror = reject;
            });
        },
        // 在methods中添加
        async convertHEICToJPG(file) {
            if (typeof window.heic2any === 'undefined') {
                console.warn('heic2any library not loaded');
                return file;
            }
            try {
                const conversionResult = await window.heic2any({
                    blob: file,
                    toType: 'image/jpeg',
                    quality: 0.5
                });
                return new File([conversionResult], file.name.replace(/\.heic$/i, '.jpg'), {
                    type: 'image/jpeg',
                    lastModified: Date.now()
                });
            } catch (error) {
                console.error('HEIC conversion failed:', error);
                return file;
            }
        },
        // 填报申请弹窗按钮
        async submitToApply() {
            if (this.isSubmitting) return;
            this.isSubmitting = true;

            if(!this.selectedFile){
                alert('请先提供照片！')
            }
            // 显示加载提示
            Toast.loading({
                message: '正在上传图片...',
                forbidClick: true
            });
            
            // 点击确定  将图片传到阿里云上
            try {
                // 压缩图片
                const fileName = `yunzhongH5-App-Picture/${new Date().getTime()}-${this.selectedFile.name}`;
                const result = await this.ossClient.put(fileName, this.selectedFile);
                console.log('上传到阿里云 OSS 成功', result);
                // 获取阿里云图片地址
                let fileUrl = result.url
                // // 获取阿里云图片地址
                // let baseUrl = result.url;

                // // 构建带有图片处理参数的 URL，这里将图片质量压缩到 80%
                // let fileUrl = `${baseUrl}?x-oss-process=image/quality,q_80`;
                Toast('图片已上传到阿里云')
                const apiResult = await addDishSampleApi({
                    dishName: this.dishInfo.dishName,
                    dishImage: fileUrl,
                    description: this.dishInfo.description,
                    remarks: this.dishInfo.remarks
                });

                if (apiResult.code === 200) {
                    this.$router.push('/preserveDishes');
                    Toast.success('提交成功');
                }
                // const params = {
                //     dishName: this.dishInfo.dishName,
                //     dishImage: fileUrl,
                //     description: this.dishInfo.description,
                //     remarks: this.dishInfo.remarks
                // }
                // addDishSampleApi(params).then(res => {
                //     this.isSubmitting = false
                //     if (res.code === 200) {
                //         console.log(res, '红烧肉', params)
                //         this.showTipsSingle = false
                //          // 关闭 loading 提示
                //         Toast.clear();
                //         this.$router.push({
                //             path: '/preserveDishes'
                //         })
                //     }else{
                //         // 如果接口返回错误，提示用户
                //         Toast('提交失败，请重试');
                //     }
                // })

            } catch (error) {
                console.error('上传到阿里云 OSS 失败', error);
                Toast('提交失败，请重试');
            } finally {
                // 无论成功或失败，最终都关闭 loading 提示
                Toast.clear();
                this.isSubmitting = false
            }

            
        },
        // 修改
        async submitToEdit() {
            if (this.isSubmitting) {
                return
            }
            this.isSubmitting = true;
            try {
                Toast.loading({ message: '提交中...' });

                // 统一处理图片修改逻辑
                if (this.uploadImg !== this.dishInfo.dishImage) {
                    // const compressedFile = await this.compressImage(this.selectedFile, 0.8);
                    const ossResult = await this.ossClient.put(
                        `yunzhongH5-App-Picture/${new Date().getTime()}-${this.selectedFile.name}`,
                        this.selectedFile
                    );
                    this.dishInfo.dishImage = ossResult.url;
                    // let editBaseUrl = ossResult.url;
                    // // 构建带有图片处理参数的 URL，这里将图片质量压缩到 80%
                    // this.dishInfo.dishImage = `${editBaseUrl}?x-oss-process=image/quality,q_80`;
                }

                const apiResult = await updateDishSampleApi({
                    id: this.dishId,
                    dishName: this.dishInfo.dishName,
                    dishImage: this.dishInfo.dishImage,
                    description: this.dishInfo.description,
                    remarks: this.dishInfo.remarks
                });

                if (apiResult.code === 200) {
                    this.$router.push('/preserveDishes');
                    Toast('修改成功')
                } else {
                    Toast('提交失败，请重试');
                }
            } catch (error) {
                console.error('操作失败', error);
                Toast('提交失败，请重试');
            } finally {
                this.isSubmitting = false;
                Toast.clear();
            }
        },

        // 接口  菜品留存信息
        getOneDishSample(dishId) {
            this.loading = true
            getDishSampleByIdApi(dishId).then(res => {
                if (res.code === 200) {
                    this.loading = false
                    this.dishInfo = res.data
                    this.uploadImg=this.dishInfo.dishImage
                } else {
                    Toast(res.message)
                }
            })
        },

    },
    beforeDestroy() {
        console.log('index')
        window.removeEventListener('scroll', this.onLoad, true)
    }
}
</script>

<style lang="less" scoped>
span,
p {
    padding: 0;
    margin: 0;
}


.content {
    overflow: hidden;
    margin-bottom: 10px;
    background: #ffffff;
    height: 100%;
    // padding-bottom: 50px;
    // margin-top: 48px;

}
.imageBox_Border{
    border: 2px dashed #e5e5e5;
    margin: 24px;
    height: 240px;
}
.imageBox_noBorder{
    border: none;
    margin: 0px;
    height: 376;
}
.imageBox {
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    background-color: #F9F9F9;

    .camera {
        width: 56px;
        height: 50px;
    }

    div {
        font-size: 12px;
        margin-top: 20px;
    }
    .picture{
        // 修改为以下样式
        width: 100%;
        height: 376px;
        object-fit: cover; 
    }
}

.recordList {
    background: #ffffff;
    // padding-top: 24px;
    padding-left: 24px;
    padding-right: 24px;

    // height: 100%;
    // overflow: auto;
    .applyTime {
        display: flex;
        align-items: center;
        height: 40px;
    }

    .name {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .label {
        font-size: 13px;
        color: #999999;
        line-height: 13px;
        width: 80px;
    }

    .text {
        font-size: 13px;
        color: #000000;
        line-height: 13px;
        margin-left: 10px;
    }

    ::v-deep .name .van-cell {
        padding: 0px;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #e5e5e5;
    }

    ::v-deep .van-cell__title,
    .van-field__label {
        font-size: 13px;
        color: #999999;
        width: 80px;
    }

    ::v-deep .describe .van-cell {
        margin-top: 20px;
        padding: 12px;
        // height: 84px;
        border: 1px solid #e5e5e5;
    }

    ::v-deep .van-field__control:disabled {
        color: #000000;
        -webkit-text-fill-color: #000000;
    }


}
// 确认填报
.applyBtn {
    padding: 24px;
}
.page_submit_btn {
    width: 100%;
    height: 45px;
    border: none;
    color: #fff;
    font-size: 15px;
    background: #047DCB;
    border-radius: 45px;
    text-align: center;
}

/*清浮动*/
.clearfix:after {
    content: '';
    display: block;
    clear: both;
}

.clearfix {
    zoom: 1;
}

// 无数据
.empty_content {
    height: 70vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    color: #000000;
    font-size: 16px;
    background: #ffffff;
}

.mr12 {
    margin-right: 12px;
}

.mt19 {
    margin-top: 19px;
}

// 弹窗
.top_title {
    width: 100%;
    height: 30px;
    line-height: 30px;
    color: #000;
    font-size: 15px;
    text-align: center;
    margin-top: 60px;
    margin-bottom: 30px;
}

// 弹出按钮
.sub_btn {
    width: 80%;
    height: 44px;
    line-height: 44px;
    text-align: center;
    border-radius: 22px;
    color: #fff;
    background: #047DCB;
    margin: 8px auto;
    font-size: 15px;
    &.disabled {
        opacity: 0.6;
        pointer-events: none;
    }
}
</style>